<?php

namespace Home\DAO;

use Home\Service\IdGenService;
use Home\Service\PinyinService;
use Home\Service\WeixinAPIService;

/**
 * 运单 DAO
 *
 * @author 李静波
 */
class ExpressDAO extends PSIBaseDAO {
	private $LOG_CATEGORY = "运单管理";

	/**
	 * 单据状态标志转化为显示文字
	 */
	private function billStatusCodeToLable($status) {
		switch ($status) {
			case 100 :
				return "待收件";
			case 200 :
				return "已收件";
			case 300 :
				return "货物达到仓库";
			case 400 :
				return "派送中";
			case 500 :
				return "已签收";
			default :
				return "";
		}
	}

	/**
	 * 付款方式编码转化为显示文字
	 */
	private function paymentCodeToLabel($payment) {
		switch ($payment) {
			case 10 :
				return "现金";
			case 20 :
				return "到付";
			case 30 :
				return "月结";
			default :
				return "";
		}
	}

	/**
	 * 运单查询
	 */
	public function query($params) {
		$ref = $params["ref"];
		
		$db = M();
		
		$sql = "select ref, rec_name, rec_address, rec_tel, send_name, send_address, send_tel,
					cargo, is_fragile, freight, payment, claim_value, cargo_money, memo, customer_id,
					status, start_place, dest_place
				from t_express_bill
				where ref = '%s' ";
		$data = $db->query($sql, $ref);
		
		if (! $data) {
			return null;
		}
		
		$v = $data[0];
		$result = array();
		
		$result["ref"] = $v["ref"];
		$result["recName"] = $v["rec_name"];
		$result["recAddress"] = $v["rec_address"];
		$result["recTel"] = $v["rec_tel"];
		$result["sendName"] = $v["send_name"];
		$result["sendAddress"] = $v["send_address"];
		$result["sendTel"] = $v["send_tel"];
		$result["cargo"] = $v["cargo"];
		$result["isFragile"] = $v["is_fragile"] == 1 ? "易碎品" : "";
		$result["freight"] = $v["freight"];
		$result["payment"] = $this->paymentCodeToLabel($v["payment"]);
		$result["claimValue"] = $v["claim_value"];
		$result["cargoMoney"] = $v["cargo_money"];
		$result["memo"] = $v["memo"];
		$result["status"] = $this->billStatusCodeToLable($v["status"]);
		$result["startPlace"] = $v["start_place"];
		$result["destPlace"] = $v["dest_place"];
		
		return $result;
	}

	private function getDistrictName($db, $id) {
		$sql = "select p.name as province_name, c.name as city_name, d.name as district_name
				from t_province p, t_city c, t_district d
				where p.id = c.province_id and c.id = d.city_id
					and d.id = '%s'
				";
		$data = $db->query($sql, $id);
		if ($data) {
			$v = $data[0];
			return $v["province_name"] . $v["city_name"] . $v["district_name"];
		} else {
			return "";
		}
	}

	/**
	 * 客户通过微信寄件
	 */
	public function apply($params) {
		$startPlaceId = $params["startPlace"];
		$destPlaceId = $params["destPlace"];
		$recName = $params["recName"];
		$recAddress = $params["recAddress"];
		$recTel = $params["recTel"];
		$sendName = $params["sendName"];
		$sendAddress = $params["sendAddress"];
		$sendTel = $params["sendTel"];
		$cargo = $params["cargo"];
		$fragile = $params["fragile"];
		$claimValue = $params["claimValue"];
		$cargoMoney = $params["cargoMoney"];
		$memo = $params["memo"];
		
		$ws = new WeixinAPIService();
		$openId = $ws->getOpenIdFromSession();
		
		if (! $openId) {
			return $this->bad("用户没有获得微信OpenId，无法寄件");
		}
		
		$db = M();
		$db->startTrans();
		
		$ud = new UserDAO();
		$defaultCompanyId = $ud->getDefaultCompanyId();
		$defaultDataOrg = $ud->getDefaultDataOrg();
		$idGen = new IdGenService();
		
		// 检查客户是否存在
		$sql = "select id, name from t_customer where weixin_id = '%s' ";
		$data = $db->query($sql, $openId);
		if (! $data) {
			// 客户首次寄件，客户资料里面没有该客户的信息，则需要自动新建客户资料
			$customerId = $idGen->newId($db);
			
			// 取默认的微信用户分类
			$sql = "select id from t_customer_category where name = '微信用户默认分类'";
			$data = $db->query($sql);
			$categoryId = null;
			if (! $data) {
				// 没有该默认分类，自动新建
				$categoryId = $idGen->newId($db);
				$sql = "insert into t_customer_category(id, code, name, parent_id, data_org, company_id) 
						values('%s', '%s', '微信用户默认分类', null, '%s', '%s')";
				$rc = $db->execute($sql, $categoryId, $categoryId, $defaultDataOrg, 
						$defaultCompanyId);
				if ($rc === false) {
					$db->rollback();
					return $this->sqlError(__LINE__);
				}
			} else {
				$categoryId = $data[0]["id"];
			}
			
			$ps = new PinyinService();
			$pinyin = $ps->toPY($sendName);
			
			$sql = "insert into t_customer(id, category_id, code, name, py, data_org, 
						company_id, weixin_id, address, mobile01)
					values ('%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s')";
			$rc = $db->execute($sql, $customerId, $categoryId, $customerId, $sendName, $pinyin, 
					$defaultDataOrg, $defaultCompanyId, $openId, $sendAddress, $sendTel);
			if ($rc === false) {
				$db->rollback();
				return $this->sqlError(__LINE__);
			}
		} else {
			$customerId = $data[0]["id"];
		}
		
		$id = $idGen->newId($db);
		
		$startPlace = $this->getDistrictName($db, $startPlaceId);
		$destPlace = $this->getDistrictName($db, $destPlaceId);
		
		$sql = "insert into t_express_bill (id, ref, rec_name, rec_address, rec_tel, send_name,
					send_address, send_tel, cargo, is_fragile, bill_dt, freight, payment,
					claim_value, cargo_money, status, memo, data_org, company_id, customer_id,
					start_place, dest_place, rec_district_id, send_district_id)
				values ('%s', '%s', '%s', '%s', '%s', '%s',
					'%s', '%s', '%s', %d, now(), %f, %d,
					%f, %f, 100, '%s', '%s', '%s', '%s',
					'%s', '%s', '%s', '%s')";
		$rc = $db->execute($sql, $id, $ref, $recName, $recAddress, $recTel, $sendName, $sendAddress, 
				$sendTel, $cargo, $fragile, $freight, $payment, $claimValue, $cargoMoney, $memo, 
				$defaultDataOrg, $defaultCompanyId, $customerId, $startPlace, $destPlace, 
				$startPlaceId, $destPlaceId);
		if ($rc === false) {
			$db->rollback();
			return $this->sqlError(__LINE__);
		}
		
		// 运单跟踪信息
		$userId = $ud->getDefaultUserId();
		
		$sql = "insert into t_express_tracing (ref, bill_id, status_before, status_after,
				changed_dt, op_user_id, memo)
				values ('%s', '%s', 0, 100, now(), '%s', '从微信端寄件')";
		$rc = $db->execute($sql, $ref, $id, $userId);
		if ($rc === false) {
			$db->rollback();
			return $this->sqlError(__LINE__);
		}
		
		$db->commit();
		
		return $this->ok();
	}

	/**
	 * 获得OpenId对应客户的信息，姓名、电话、地址等
	 *
	 * @param string $openId
	 *        	微信OpenId
	 */
	public function getMyInfo($openId) {
		$result = array(
				"isExpressMan" => - 1
		);
		
		$db = M();
		
		// 判断是否还有未绑定微信的快递员记录
		// 如果有，则在前端显示绑定快递员的输入验证码的界面
		$sql = "select count(*) as cnt from t_express_man
				where wx_id is null or wx_id = '' ";
		$data = $db->query($sql);
		$cnt = $data[0]["cnt"];
		
		$result["expressManCanBind"] = $cnt;
		
		// 判断当前用户是不是快递员
		$sql = "select name, mobile, bind_code
				from t_express_man
				where wx_id = '%s' ";
		$data = $db->query($sql, $openId);
		if ($data) {
			$result["name"] = $data[0]["name"];
			$result["tel"] = $data[0]["mobile"];
			$result["isExpressMan"] = 1;
			$result["bindCode"] = $data[0]["bind_code"];
			
			return $result;
		}
		
		// 判断当前用户是不是普通用户
		$sql = "select name, mobile01, address
				from t_customer
				where weixin_id = '%s' ";
		
		$data = $db->query($sql, $openId);
		
		if ($data) {
			$result["name"] = $data[0]["name"];
			$result["tel"] = $data[0]["mobile01"];
			$result["address"] = $data[0]["address"];
			
			$result["isExpressMan"] = 0;
			
			return $result;
		}
		
		return $result;
	}

	public function editMyInfo($params) {
		$openId = $params["openId"];
		$name = $params["name"];
		$address = $params["address"];
		$tel = $params["tel"];
		$bindCode = $params["bindCode"];
		
		$db = M();
		$db->startTrans();
		
		if ($bindCode) {
			$sql = "select id, wx_id from t_express_man where bind_code = '%s' ";
			$data = $db->query($sql, $bindCode);
			if (! $data) {
				$db->rollback();
				return $this->bad("效验码错误");
			}
			
			$id = $data[0]["id"];
			$wxId = $data[0]["wx_id"];
			$queryParams = array();
			$sql = "";
			if (! $wxId) {
				// 首次设置信息
				$sql = "update t_express_man
						set name = '%s', mobile = '%s', wx_id = '%s'
						where id = '%s'";
				$queryParams[] = $name;
				$queryParams[] = $tel;
				$queryParams[] = $openId;
				$queryParams[] = $id;
			} else {
				$sql = "update t_express_man
						set name = '%s', mobile = '%s'
						where id = '%s' ";
				$queryParams[] = $name;
				$queryParams[] = $tel;
				$queryParams[] = $id;
			}
			$db->execute($sql, $queryParams);
			
			$db->commit();
			return $this->ok();
		}
		
		// 当前用户是普通用户
		
		$sql = "select id from t_customer where weixin_id = '%s' ";
		$data = $db->query($sql, $openId);
		if ($data) {
			$sql = "update t_customer
					set name = '%s', mobile01 = '%s', address = '%s'
					where weixin_id = '%s' ";
			$rc = $db->execute($sql, $name, $tel, $address, $openId);
			if ($rc === false) {
				$db->rollback();
				return $this->sqlError(__LINE__);
			}
		} else {
			// 用户首次保存数据
			$ud = new UserDAO();
			$defaultCompanyId = $ud->getDefaultCompanyId();
			$defaultDataOrg = $ud->getDefaultDataOrg();
			
			$idGen = new IdGenService();
			
			$customerId = $idGen->newId($db);
			
			// 取默认的微信用户分类
			$sql = "select id from t_customer_category where name = '微信用户默认分类'";
			$data = $db->query($sql);
			$categoryId = null;
			if (! $data) {
				// 没有该默认分类，自动新建
				$categoryId = $idGen->newId($db);
				$sql = "insert into t_customer_category(id, code, name, parent_id, data_org, company_id) 
						values('%s', '微信用户默认分类', '微信用户默认分类', null, '%s', '%s')";
				$rc = $db->execute($sql, $categoryId, $defaultDataOrg, $defaultCompanyId);
				if ($rc === false) {
					$db->rollback();
					return $this->sqlError(__LINE__);
				}
			} else {
				$categoryId = $data[0]["id"];
			}
			
			$ps = new PinyinService();
			$pinyin = $ps->toPY($name);
			
			$sql = "insert into t_customer(id, category_id, code, name, py, data_org, 
						company_id, weixin_id, address, mobile01)
					values ('%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s')";
			$rc = $db->execute($sql, $customerId, $categoryId, $customerId, $name, $pinyin, 
					$defaultDataOrg, $defaultCompanyId, $openId, $address, $tel);
			if ($rc === false) {
				$db->rollback();
				return $this->sqlError(__LINE__);
			}
		}
		
		$db->commit();
		
		return $this->ok();
	}

	public function queryProvince($params) {
		$db = M();
		$sql = "select id, name from t_province
				order by name";
		return $db->query($sql);
	}

	public function queryCity($params) {
		$db = M();
		
		$id = $params["id"];
		
		$sql = "select id, name from t_city
				where province_id = '%s' 
				order by name";
		return $db->query($sql, $id);
	}

	public function queryDistrict($params) {
		$db = M();
		
		$id = $params["id"];
		
		$sql = "select id, name from t_district
				where city_id = '%s'
				order by name";
		return $db->query($sql, $id);
	}
}